package com.example.dubbo.service.account.impl.demo;

import com.example.dubbo.aip.demo.AccountTblService;
import com.example.dubbo.aip.vo.demo.AccountTbl;
import com.example.dubbo.service.account.mapper.demo.AccountTblMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.RedissonRedLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 账户相关Service
 * ClassName:AccountTbl
 * Description: 用于测试Seata 分布式事务
 */
@Service(version = "1.0.0", timeout = 30000)
@Slf4j
public class AccountTblServiceImpl implements AccountTblService {
    @Resource
    private AccountTblMapper accountTblMapper;

    @Autowired
    RedissonClient redisson;

    @Override
    public void subtractAccount() {
        AccountTbl entity = new AccountTbl();
        entity.setId(1);
        entity.setUserId("1001");
        entity.setMoney(9000);
        accountTblMapper.updateByPrimaryKey(entity);
    }

    @Override
    public boolean fechargeAccount(Integer cnt) {
        //加锁
        RedissonRedLock redLock = new RedissonRedLock(redisson.getLock("dec_store_lock_"));
        boolean isLock;
        try {
            isLock = redLock.tryLock(500, 5000, TimeUnit.MILLISECONDS);
            log.info("获取锁:--{}",isLock);
            if (isLock) {
                log.info("接收到参数:--{}",cnt);
                AccountTbl entity =new AccountTbl();
                entity.setId(1);
                entity=accountTblMapper.selectByPrimaryKey(entity);
                entity.setMoney(entity.getMoney()+1);
                accountTblMapper.updateByPrimaryKeySelective(entity);
                return true;
            }
            return false;
        } catch (InterruptedException e) {
            log.error("加锁异常：{}",e.getMessage());
            return false;
        } finally {
            // 无论如何, 最后都要解锁
            System.out.println("");
            redLock.unlock();
        }



    }
}